﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using CMN.Entity;
namespace CMN.Common
{
    public  class ImageHelper
    {

        /// <summary>
        /// Image Rotation
        /// </summary>
        /// <param name="oldImage">A <see cref="System.Drawing.Image"/> source</param>
        /// <param name="angle">Rotate angle(only -180, -90, 90, 180,)</param>
        /// <returns></returns>
        public  Bitmap RotateImage(Image oldImage, float angle)
        {
            float na = Math.Abs(angle);
            if (na != 90 && na != 180)
                throw new ArgumentException("angle could only be -180, -90, 90, 180 degrees, but now it is " + angle.ToString() + " degrees!");

            #region -Unused(for any degrees)-
            //double radius = angle * Math.PI / 180.0;
            //double cos = Math.Cos(radius);
            //double sin = Math.Sin(radius);

            //int ow = oldImage.Width;
            //int oh = oldImage.Height;
            //int nw = (int)(Math.Abs(ow * cos) + Math.Abs(oh * sin));
            //int nh = (int)(Math.Abs(ow * sin) + Math.Abs(oh * cos));
            #endregion

            int ow = oldImage.Width;
            int oh = oldImage.Height;
            int nw = ow;
            int nh = oh;
            //90/-90
            if (na == 90)
            {
                nw = oh;
                nh = ow;
            }

            Bitmap bmp = new Bitmap(nw, nh);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.InterpolationMode = InterpolationMode.Bilinear;
                g.SmoothingMode = SmoothingMode.HighQuality;

                Point offset = new Point((nw - ow) / 2, (nh - oh) / 2);
                Rectangle rect = new Rectangle(offset.X, offset.Y, ow, oh);
                Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
                g.TranslateTransform(center.X, center.Y);
                g.RotateTransform(angle);
                g.TranslateTransform(-center.X, -center.Y);
                g.DrawImage(oldImage, rect);
                g.ResetTransform();
                g.Save();
            }
            return bmp;
        }
        /// <summary>
        /// Generate the new bitmap
        /// </summary>
        /// <param name="oldImage">A <see cref="System.Drawing.Image"/> source</param>
        /// <param name="cut">The <see cref="BitmapCutter.Core.API.Cutter"/></param>
        /// <returns></returns>
        public  Bitmap GenerateBitmap(Image oldImage, Cutter cut)
        {
            if (oldImage == null)
                throw new ArgumentNullException("oldImage");

            Image newBitmap = new Bitmap(cut.SaveWidth, cut.SaveHeight);
            //Re-paint the oldImage
            using (Graphics g = Graphics.FromImage(newBitmap))
            {
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(oldImage, new Rectangle(0, 0, cut.SaveWidth, cut.SaveHeight), new Rectangle(0, 0, cut.Width, cut.Height), GraphicsUnit.Pixel);
                g.Save();
            }

            Bitmap bmp = new Bitmap(cut.CutterWidth, cut.CutterHeight);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(newBitmap, 0, 0, new Rectangle(cut.X, cut.Y, cut.CutterWidth, cut.CutterHeight), GraphicsUnit.Pixel);
                g.Save();
                newBitmap.Dispose();
            }
            return bmp;
        }



        /// <summary>
        /// 切割后生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="toW">缩略图最终宽度</param>
        /// <param name="toH">缩略图最终高度</param>
        /// <param name="X">X坐标（zoom为1时）</param>
        /// <param name="Y">Y坐标（zoom为1时）</param>
        /// <param name="W">选择区域宽（zoom为1时）</param>
        /// <param name="H">选择区域高（zoom为1时）</param>
        

        public  void MakeMyThumbs(string originalImagePath, string thumbnailPath, int toW, int toH, int X, int Y, int W, int H)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = toW;
            int toheight = toH;
            int x = X;
            int y = Y;
            int ow = W;
            int oh = H;            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, originalImage.RawFormat);

            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 高自量保存
        /// </summary>
        /// <param name="img"></param>
        /// <param name="savePath"></param>
        public void ImgSaveHigh(Image img, string savePath)
        {
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(img.Width , img.Height );
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(img, new System.Drawing.Rectangle(0, 0, img.Width , img.Height ),
            new System.Drawing.Rectangle(0, 0, img.Width, img.Height),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(savePath, img.RawFormat);

            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                img.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 低质量保存图片
        /// </summary>
        /// <param name="img">原图片</param>
        /// <param name="savePath">保存地址</param>
        /// <param name="flag">缩放大小</param>
        public void ImgSaveLow( Image img,string savePath,int flag)
        {
            
                        //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(img.Width / flag, img.Height / flag);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;//设置高质量插值法
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;//设置高质量,低速度呈现平滑程度
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(img, new System.Drawing.Rectangle(0, 0, img.Width / flag, img.Height / flag),
            new System.Drawing.Rectangle(0,0,img.Width,img.Height),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(savePath, img.RawFormat);

            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                img.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 低质量保存图片
        /// </summary>
        /// <param name="img">原图片</param>
        /// <param name="savePath">保存地址</param>
        /// <param name="flag">缩放大小</param>
        public void ImgSaveHigh(Image img, string savePath, int flag)
        {

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(img.Width / flag, img.Height / flag);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;//设置高质量,低速度呈现平滑程度
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(img, new System.Drawing.Rectangle(0, 0, img.Width / flag, img.Height / flag),
            new System.Drawing.Rectangle(0, 0, img.Width, img.Height),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(savePath, img.RawFormat);

            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                img.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImage">源图</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="photoWidth">最终缩略图宽度</param>
        /// <param name="height">最终缩略图高度</param>
        /// <param name="mode">生成缩略图的方式
        /// <code>HW:指定高宽缩放（可能变形）</code>
        /// <code>W:指定宽，高按比例  </code>
        /// <code>H:指定高，宽按比例</code>
        /// <code>CUT:指定高宽裁减（不变形） </code>
        /// <code>FILL:填充</code>
        /// </param> 
        public  void Image2Thumbs(System.Drawing.Image originalImage, string thumbnailPath, int photoWidth, int photoHeight, string mode)
        {
            #region 开始画图
            int lastPhotoWidth = photoWidth;//最后缩略图的宽度
            int lastPhotoHeight = photoHeight;//最后缩略图的高度

            int toWidth = photoWidth;//原图片被压缩的宽度
            int toHeight = photoHeight;//原图片被压缩的高度

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            int bg_x = 0;
            int bg_y = 0;
            switch (mode.ToUpper())
            {
                case "FILL"://压缩填充至指定区域                
                    toHeight = photoHeight;
                    toWidth = toHeight * ow / oh;
                    if (toWidth > photoWidth)
                    {
                        toHeight = toHeight * photoWidth / toWidth;
                        toWidth = photoWidth;
                    }
                    bg_x = (photoWidth - toWidth) / 2;
                    bg_y = (photoHeight - toHeight) / 2;
                    break;
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toHeight = lastPhotoHeight = originalImage.Height * photoWidth / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    toWidth = lastPhotoWidth = originalImage.Width * photoHeight / originalImage.Height;
                    break;
                case "CUT"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)lastPhotoWidth / (double)lastPhotoHeight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * lastPhotoWidth / lastPhotoHeight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * photoHeight / lastPhotoWidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(lastPhotoWidth, lastPhotoHeight);//新建一个bmp图片
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);//新建一个画板
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.Clear(System.Drawing.Color.White);//白色
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, toWidth, toHeight),//在指定位置并且按指定大小绘制原图片的指定部分
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {

                bitmap.Dispose();
                g.Dispose();
            }
            #endregion
        }

        /**/
        /// <summary>  
        /// 干扰度（百分之几）  
        /// </summary>  
        private  int fineness = 0;
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="checkCode"></param>
        /// <param name="imgWidth"></param>
        /// <param name="imgHeight"></param>
        /// <param name="fontSize"></param>
        /// <returns></returns>
        public  Image CreateCheckCodeImage(string checkCode, int imgWidth, int imgHeight, int fontSize)
        {

            //将验证码生成图片显示
            if (string.IsNullOrEmpty(checkCode))
                return null;
            Random rnd = new Random();
            System.Drawing.Bitmap image = null;
            image = new System.Drawing.Bitmap(imgWidth, imgHeight);
            //DisturbBitmap(image);
            Graphics g = Graphics.FromImage(image);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            try
            {
                //生成随机生成器 
                Random random = new Random();

                //清空图片背景色 
                // g.Clear(Color.White);

                StringFormat sf = new StringFormat(StringFormatFlags.NoClip);
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                List<CMN.Entity.FontStyle> a = new List<CMN.Entity.FontStyle>(15);
                a.Add(new CMN.Entity.FontStyle(Color.Red, fontSize));
                a.Add(new CMN.Entity.FontStyle(Color.Green, fontSize));
                a.Add(new CMN.Entity.FontStyle(Color.Blue, fontSize));
                a.Add(new CMN.Entity.FontStyle(Color.DarkOrange, fontSize));
                a.Add(new CMN.Entity.FontStyle(Color.Brown, fontSize));
                a.Add(new CMN.Entity.FontStyle(Color.DarkSlateBlue, fontSize));
                a.Add(new CMN.Entity.FontStyle(Color.SteelBlue, fontSize));

                //List<FontStyle> a = GetRndColor(checkCode.Length);
                CMN.Entity.FontStyle fontcolor = a[random.Next(0, a.Count)];
                for (int i = 0; i < 3; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(fontcolor.FontColor), x1, y1, x2, y2);
                }

                //画文字
                int charX, CharY, charSize, charFontSize;

                //移除宽度
                int delwidth = 0;
                //旋转角度
                int rotatefont = 0;
                Matrix mat = new Matrix();
                for (int i = 0; i < checkCode.Length; i++)
                {
                    if (i != 0)
                    {
                        delwidth = rnd.Next(fontSize / 4, fontSize / 3);
                    }
                    rotatefont = random.Next(-60, 60);
                    charFontSize = rnd.Next(fontSize - 5, fontSize);
                    charSize = (imgWidth - 5) / checkCode.Length;
                    charX = charSize * (i) + rnd.Next(2, 6);
                    CharY = rnd.Next(1, imgHeight - (charFontSize)) - 10;

                    mat.RotateAt(rotatefont, new PointF(charX, fontSize));
                    g.Transform = mat;

                    //路径
                    string path = string.Concat(Utils.GetServerPath(), "App_Data//font//elephant.ttf");
                    //读取字体文件
                    System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
                    pfc.AddFontFile(path);

                    //设置字体
                    g.DrawString(checkCode[i].ToString(), new System.Drawing.Font(pfc.Families[0], charFontSize, (System.Drawing.FontStyle.Regular)), new SolidBrush(fontcolor.FontColor), charX - delwidth, CharY);

                    mat.RotateAt(rotatefont * -1, new PointF(charX, fontSize));
                    g.Transform = mat;
                }

                g.Transform = new Matrix();

                //画图片的边框线 
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                g.Dispose();
                return image;

            }
            finally
            {
                g.Dispose();
            }

            return image;
        }


        /**/
        /// <summary>  
        /// 为图片设置干扰点  
        /// </summary>  
        /// <param name="bitmap"></param>  
        private  void DisturbBitmap(Bitmap bitmap)
        {
            Random rand = new Random();
            int iRed = rand.Next(200, 255);
            int iGreen = rand.Next(200, 255);
            int iBlue = rand.Next(200, 255);
            int iAlpha = rand.Next(0, 100);
            // 通过随机数生成  
            Random random = new Random();
            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    if (random.Next(100) <= fineness)
                    {
                        //设置干扰点  
                        iAlpha = rand.Next(0, 100);
                        iRed = rand.Next(50, 150);
                        iGreen = rand.Next(50, 150);
                        iBlue = rand.Next(50, 150);
                        bitmap.SetPixel(i, j, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                    }
                    else
                    {
                        //绘制背景色  
                        iAlpha = rand.Next(0, 100);
                        iRed = rand.Next(240, 255);
                        iGreen = rand.Next(200, 255);
                        iBlue = rand.Next(200, 255);
                        bitmap.SetPixel(i, j, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                    }
                }
            }
            //画边框  
            iAlpha = rand.Next(0, 100);
            iRed = rand.Next(0, 0);
            iGreen = rand.Next(0, 255);
            iBlue = rand.Next(0, 255);
            for (int i = 0; i < bitmap.Width; i++)
            {
                bitmap.SetPixel(i, 0, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                bitmap.SetPixel(i, 1, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                bitmap.SetPixel(i, bitmap.Height - 1, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                bitmap.SetPixel(i, bitmap.Height - 2, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
            }
            for (int i = 0; i < bitmap.Height; i++)
            {
                bitmap.SetPixel(0, i, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                bitmap.SetPixel(1, i, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                bitmap.SetPixel(bitmap.Width - 1, i, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
                bitmap.SetPixel(bitmap.Width - 2, i, Color.FromArgb(iAlpha, iRed, iGreen, iBlue));
            }
        }

        /// <summary>
        /// 缩略图，按高度和宽度来缩略
        /// </summary>
        /// <param name="image"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public  Image Scale(Image image, Size size)
        {
            return image.GetThumbnailImage(size.Width, size.Height, null, new IntPtr());
        }

        /// <summary>
        /// 缩略图，按倍数来缩略
        /// </summary>
        /// <param name="image">原图</param>
        /// <param name="multiple">放大或缩小的倍数，负数表示缩小，正数表示放大</param>
        /// <returns></returns>
        public  Image Scale(Image image, Int32 multiple)
        {
            Int32 newWidth;
            Int32 newHeight;
            Int32 absMultiple = Math.Abs(multiple);
            if (multiple == 0)
            {
                return image.Clone() as Image;
            }
            if (multiple < 0)
            {
                newWidth = image.Width / absMultiple;
                newHeight = image.Height / absMultiple;
            }
            else
            {
                newWidth = image.Width * absMultiple;
                newHeight = image.Height * absMultiple;
            }
            return image.GetThumbnailImage(newWidth, newHeight, null, new IntPtr());
        }
        /// <summary>
        /// 固定宽度缩略
        /// </summary>
        /// <param name="image"></param>
        /// <param name="width"></param>
        /// <returns></returns>
        public  Image ScaleFixWidth(Image image, Int32 width)
        {
            Int32 newWidth = width;
            Int32 newHeight;
            Double tempMultiple = (Double)newWidth / (Double)image.Width;
            newHeight = (Int32)(((Double)image.Height) * tempMultiple);
            Image newImage = new Bitmap(newWidth, newHeight);
            using (Graphics newGp = Graphics.FromImage(newImage))
            {
                
                newGp.CompositingQuality = CompositingQuality.HighSpeed;
                //设置高质量插值法
                newGp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
                //设置高质量,低速度呈现平滑程度
                newGp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                //清空画布并以透明背景色填充
          
                newGp.PixelOffsetMode = PixelOffsetMode.HighQuality;
                newGp.Clear(Color.Transparent);
                newGp.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight));
            }
            return newImage;
        }


       

        /// <summary>
        /// 固定高度缩略
        /// </summary>
        /// <param name="image"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public  Image ScaleFixHeight(Image image, Int32 height)
        {
            Int32 newWidth;
            Int32 newHeight = height;

            Double tempMultiple = (Double)newHeight / (Double)image.Height;
            newWidth = (Int32)(((Double)image.Width) * tempMultiple);
            Image newImage = new Bitmap(newWidth, newHeight);
            using (Graphics newGp = Graphics.FromImage(newImage))
            {
                newGp.CompositingQuality = CompositingQuality.HighSpeed;
                //设置高质量插值法
                newGp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
                //设置高质量,低速度呈现平滑程度
                newGp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                //清空画布并以透明背景色填充
                newGp.PixelOffsetMode = PixelOffsetMode.HighQuality;
                newGp.Clear(Color.Transparent);
                newGp.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight));
            }
            return newImage;
        }
        /// <summary>
        /// 裁减缩略，根据固定的高度和宽度
        /// </summary>
        /// <param name="image"></param>
        /// <param name="width"></param>
        /// <param name="heigth"></param>
        /// <returns></returns>
        public  Image ScaleCut(Image image, Int32 width, Int32 height)
        {
            int x = 0;
            int y = 0;
            int ow = image.Width;
            int oh = image.Height;
            if (width >= ow && height >= oh)
            {
                return image;
            }
            //如果结果要比原来的宽
            if (width > ow)
            {
                width = ow;
            }
            if (height > oh)
            {
                height = oh;
            }

            if ((double)image.Width / (double)image.Height > (double)width / (double)height)
            {
                oh = image.Height;
                ow = image.Height * width / height;
                y = 0;
                x = (image.Width - ow) / 2;
            }
            else
            {
                ow = image.Width;
                oh = image.Width * height / width;
                x = 0;
                y = (image.Height - oh) / 2;
            }
            Image newImage = new Bitmap(width, height);
            using (Graphics newGp = Graphics.FromImage(newImage))
            {
                newGp.CompositingQuality = CompositingQuality.HighSpeed;
                //设置高质量插值法
                newGp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
                //设置高质量,低速度呈现平滑程度
                newGp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                //清空画布并以透明背景色填充
                newGp.Clear(Color.Transparent);
                newGp.DrawImage(image, new Rectangle(0, 0, width, height),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);
            }
            return newImage;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public  void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 打水印，在某一点
        /// </summary>
        /// <param name="image"></param>
        /// <param name="waterImagePath"></param>
        /// <param name="p"></param>
        public  void Makewater(Image image, String waterImagePath, Point p)
        {
            Makewater(image, waterImagePath, p, ImagePosition.TopLeft);
        }
        public  void Makewater(Image image, String waterImagePath, Point p, ImagePosition imagePosition)
        {
            using (Image warterImage = Image.FromFile(waterImagePath))
            {
                using (Graphics newGp = Graphics.FromImage(image))
                {
                    newGp.CompositingQuality = CompositingQuality.HighQuality;
                    //设置高质量插值法
                    newGp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    //设置高质量,低速度呈现平滑程度
                    newGp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    switch (imagePosition)
                    {
                        case ImagePosition.BottomLeft:
                            p.Y = image.Height - warterImage.Height - p.Y;
                            break;
                        case ImagePosition.TopRigth:
                            p.X = image.Width - warterImage.Width - p.X;
                            break;
                        case ImagePosition.BottomRight:
                            p.Y = image.Height - warterImage.Height - p.Y;
                            p.X = image.Width - warterImage.Width - p.X;
                            break;
                    }
                    newGp.DrawImage(warterImage, new Rectangle(p, new Size(warterImage.Width, warterImage.Height)));
                }
            }
        }
        public  void Makewater(Image image, String waterStr, Font font, Brush brush, Point p)
        {
            Makewater(image, waterStr, font, brush, p, ImagePosition.TopLeft);

        }
        public  void Makewater(Image image, String waterStr, Font font, Brush brush, Point p, ImagePosition imagePosition)
        {
            using (Graphics newGp = Graphics.FromImage(image))
            {
                Int32 stringWidth;
                Int32 stringHeight;
                stringHeight = (int)font.Size;
                
                //stringWidth = (int)(((float)waterStr.GetBitLength(waterStr) / (float)2) * (font.Size + 1));
                stringWidth = (int)((font.Size + 1));
                newGp.CompositingQuality = CompositingQuality.HighSpeed;
                //设置高质量插值法
                newGp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
                //设置高质量,低速度呈现平滑程度
                newGp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                //文字抗锯齿
                newGp.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                switch (imagePosition)
                {
                    case ImagePosition.BottomLeft:
                        p.Y = image.Height - stringHeight - p.Y;
                        break;
                    case ImagePosition.TopRigth:
                        p.X = image.Width - stringWidth - p.X;
                        break;
                    case ImagePosition.BottomRight:
                        p.Y = image.Height - stringHeight - p.Y;
                        p.X = image.Width - stringWidth - p.X;
                        break;
                }
                newGp.DrawString(waterStr, font, brush, p);
            }
        }
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image"></param>
        /// <param name="path"></param>
        public  void SaveImage(Image image, String path,int flag)
        {
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;
            myImageCodecInfo = ImageCodecInfo.GetImageEncoders()[0];
            myEncoder = Encoder.Quality;
            myEncoderParameters = new EncoderParameters(1);
            myEncoderParameter = new EncoderParameter(myEncoder,flag); // 0-100
            myEncoderParameters.Param[0] = myEncoderParameter;
            try
            {
                image.Save(path, myImageCodecInfo, myEncoderParameters);
            }
            finally
            {
                myEncoderParameter.Dispose();
                myEncoderParameters.Dispose();
            }
        }
    }
    public enum StringPosition
    {
        TopLeft,
        BottomLeft
    }
    public enum ImagePosition
    {
        TopLeft,
        BottomLeft,
        BottomRight,
        TopRigth
    }
}